package com.wangsai.framework.supersecurity.dubbo;

import com.alibaba.fastjson.JSON;
import com.wangsai.framework.supersecurity.core.SuperSecurityManager;
import com.wangsai.framework.supersecurity.core.context.UserContext;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

import java.util.HashMap;
import java.util.Optional;

/**
 * @author Mr.Wang
 * @description
 * @date 2021-08-15 17:52
 */
@Activate(group = CommonConstants.CONSUMER)
public class SuperSecurityDubboFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Optional<HashMap> userOptional = UserContext.currentUserOfNullable(HashMap.class);
        userOptional.ifPresent(user -> RpcContext.getContext()
                .setAttachment(SuperSecurityManager.getConfig().getUserKey(),
                        SuperSecurityManager.getUserSecure().encode(JSON.toJSONString(user))));
        return invoker.invoke(invocation);
    }
}